﻿using Aspose.Cells;
using Dapper;
using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

using Telerik.Windows.Controls;
using TruckScale.Helpers;
using TruckScale.Models;

namespace TruckScale.Views
{
  /// <summary>
  /// Interaction logic for QSWeighList.xaml
  /// </summary>
  public partial class QSWeighList : RadWindow
  {
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public DateTime? StartTime { get; set; }
    public DateTime? EndTime { get; set; }
    public List<WeighFormModel> WeighFormField { get; set; }
    public WrapPanel WeighFormWrapPanel { get; set; }
    public Dictionary<string, string> WeighFormDic { get; set; } //在xaml中被使用，动态显示自定义的名称
    public Dictionary<string, bool> WeighFormActiveDic { get; set; } //在xaml中被使用，动态显示是否被使用
    public Dictionary<string, bool> VisibleFieldDic { get; set; } = new Dictionary<string, bool>()
    {
      { "_ch", true }, { "_kh", false }, { "_kh2", false }, { "_kh3", false }, { "_kh4", false }, { "_wz", true },
      { "_by1", false }, { "_by2", false }, { "_by3", false }, { "_by4", false }, { "_by5", false },
      { "_by6", false }, { "_by7", false }, { "_by8", false }, { "_by9", false }, { "_by10", false },
      { "_weighTemplate", true }, { "_isFinish", true }
    };

    public Dictionary<string, bool> SelectedFieldDic { get; set; } = new Dictionary<string, bool>()
    {
      { "_ch", false }, { "_kh", false }, { "_kh2", false }, { "_kh3", false }, { "_kh4", false }, { "_wz", false },
      { "_by1", false }, { "_by2", false }, { "_by3", false }, { "_by4", false }, { "_by5", false },
      { "_by6", false }, { "_by7", false }, { "_by8", false }, { "_by9", false }, { "_by10", false },
      { "_weighTemplate", false }, { "_isFinish", false }
    };
    public Dictionary<string, object> SelectedValueDic { get; set; } = new Dictionary<string, object>
    {
      { "_ch", null }, { "_kh", null }, { "_kh2", null }, { "_kh3", null }, { "_kh4", null }, { "_wz", null },
      { "_by1", null }, { "_by2", null }, { "_by3", null }, { "_by4", null }, { "_by5", null },
      { "_by6", null }, { "_by7", null }, { "_by8", null }, { "_by9", null }, { "_by10", null },
      { "_weighTemplate", null }, { "_isFinish", null }
    };

    public Dictionary<string, bool> ShowFieldDic { get; set; } = new Dictionary<string, bool>()
    {
      { "_bh", false }, { "_ch", false }, { "_kh", false }, { "_kh2", false }, { "_kh3", false }, { "_kh4", false },
      { "_wz", false }, { "_dj", false }, { "_mz", false }, { "_mzsj", false }, { "_mzsby", false }, { "_pz", false },
      { "_pzsj", false }, { "_pzsby", false },{ "_jz", false }, { "_jzsj", false }, { "_bz", false },
      { "_by1", false }, { "_by2", false }, { "_by3", false }, { "_by4", false }, { "_by5", false },
      { "_by6", false }, { "_by7", false }, { "_by8", false }, { "_by9", false }, { "_by10", false },
      { "_weighbridge1", false }, { "_weighbridge2", false }, { "_weighTemplate", false }
    };

    public List<CarModel> CarList { get; set; }
    public List<GoodsModel> GoodsList { get; set; }
    public List<CustomerModel> CustomerList { get; set; }
    public List<CustomerModel> Customer2List { get; set; }
    public List<CustomerModel> Customer3List { get; set; }
    public List<CustomerModel> Customer4List { get; set; }
    public List<string> TemplateList { get; set; } = new List<string>() { "采购磅单", "销售磅单" };
    public List<string> IsFinishList { get; set; } = new List<string>() { "未完成", "已完成" };
    public List<SpareModel> By1List { get; set; }
    public List<SpareModel> By2List { get; set; }
    public List<SpareModel> By3List { get; set; }
    public List<SpareModel> By4List { get; set; }
    public List<SpareModel> By5List { get; set; }
    public List<SpareModel> By6List { get; set; }
    public List<SpareModel> By7List { get; set; }
    public List<SpareModel> By8List { get; set; }
    public List<SpareModel> By9List { get; set; }
    public List<SpareModel> By10List { get; set; }
    public QSWeighList()
    {
      InitializeComponent();
      DataContext = this;

      StartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
      EndTime = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").ToString()).AddSeconds(-1);
      //把字段名称（自定义过的）放到字段字典里
      WeighFormField = WeighFormModel.SelectAllField();
      WeighFormDic = WeighFormField.Where(item => !string.IsNullOrEmpty(item.WeighFormKey))
        .ToDictionary(item => item.WeighFormKey, item => item.WeighFormValue);
      WeighFormActiveDic = WeighFormField.Where(item => !string.IsNullOrEmpty(item.WeighFormKey))
        .ToDictionary(item => item.WeighFormKey, item => item.IsActive);

      //根据规则判断是否把字段显示到查询条件里

      //默认显示了 车号、物资、称重模板、是否完成
      CarList = CarModel.SelectActiveCar();
      GoodsList = GoodsModel.SelectValidGoods();
      //需要按需显示 客户、备用字段
      var customerTypes = new Dictionary<string, string> { { "_kh", "采购" }, { "_kh2", "销售" }, { "_kh3", "运输" }, { "_kh4", "其他" } };

      foreach (var type in customerTypes)
      {
        var customerList = CustomerModel.SelectCustomerByType(type.Value);
        if (customerList.Count > 0)
        {
          VisibleFieldDic[type.Key] = true;
          switch (type.Key)
          {
            case "_kh":
              CustomerList = customerList;
              break;
            case "_kh2":
              Customer2List = customerList;
              break;
            case "_kh3":
              Customer3List = customerList;
              break;
            case "_kh4":
              Customer4List = customerList;
              break;
            default:
              break;
          }
        }
      }

      var spareKeys = new Dictionary<string, List<SpareModel>>
      {
          { "_by1", By1List = SpareModel.SelectSpareByKey("_by1") },
          { "_by2", By2List = SpareModel.SelectSpareByKey("_by2") },
          { "_by3", By3List = SpareModel.SelectSpareByKey("_by3") },
          { "_by4", By4List = SpareModel.SelectSpareByKey("_by4") },
          { "_by5", By5List = SpareModel.SelectSpareByKey("_by5") },
          { "_by6", By6List = SpareModel.SelectSpareByKey("_by6") },
          { "_by7", By7List = SpareModel.SelectSpareByKey("_by7") },
          { "_by8", By8List = SpareModel.SelectSpareByKey("_by8") },
          { "_by9", By9List = SpareModel.SelectSpareByKey("_by9") },
          { "_by10", By10List = SpareModel.SelectSpareByKey("_by10") }
      };

      foreach (var key in spareKeys)
      {
        if (key.Value.Count > 0)
        {
          VisibleFieldDic[key.Key] = true;
        }
      }

      //把有使用的字段勾选上
      var wfmList = WeighFormModel.SelectActiveField();
      foreach (var wfm in wfmList)
      {
        ShowFieldDic[wfm.WeighFormKey] = true;
      }

      //根据规则判断是否把字段显示到查询结果里

      //必须显示 编号、车号
      //需要按需显示 客户
      //默认显示 物资、单价、毛重、毛重时间、毛重司磅员、皮重、皮重时间、皮重司磅员、净重、净重时间、备注
      //需要按需显示 备用字段
      //默认显示 一次地磅名称、二次地磅名称、称重模板、是否完成

      //-------下面是高级查询--------------
      #region 高级查询
      WeighFormWrapPanel = new WrapPanel();
      WeighFormWrapPanel.Margin = new Thickness(5);

      foreach (var f in WeighFormField)
      {
        StackPanel sp = new StackPanel();
        sp.Orientation = Orientation.Horizontal;
        sp.Margin = new Thickness(0, 5, 10, 5);

        TextBlock tbk = new TextBlock();
        tbk.Text = f.WeighFormValue;
        tbk.FontSize = Convert.ToDouble(Global._weighConfig["MainFontSize"]);
        tbk.Width = 5 * Convert.ToDouble(Global._weighConfig["MainFontSize"]) + 4;
        tbk.VerticalAlignment = VerticalAlignment.Center;
        tbk.Margin = new Thickness(5);
        sp.Children.Add(tbk);

        string bindingName = Regex.Replace(f.WeighFormKey.Substring(1), "^[a-z]", m => m.Value.ToUpper());

        if (bindingName.Equals("Ch") || bindingName.Equals("Wz") || bindingName.Equals("Dj") || bindingName.StartsWith("Kh") ||
          (bindingName.StartsWith("By") && SpareModel.SelectSpareByKey(f.WeighFormKey).Count > 0) || bindingName.EndsWith("sby"))
        {
          RadComboBox cbx = new RadComboBox();
          cbx.ItemsPanel = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(VirtualizingStackPanel))); //解决车号数量多了卡顿的问题
          cbx.Width = 10 * Convert.ToDouble(Global._weighConfig["MainFontSize"]) + 12;
          cbx.Name = bindingName;
          cbx.IsEditable = true;
          cbx.IsTextSearchEnabled = false;
          cbx.KeyUp += Cb_KeyUp;
          //binding
          if (bindingName.Equals("Ch"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.TextProperty, binding);
            var list = CarModel.SelectActiveCar();
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "PlateNo";
            //cbx.SelectedItem = list.Find(g => g.PlateNo == WeighRecord.Ch);
          }
          if (bindingName.Equals("Wz"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = GoodsModel.SelectValidGoods();
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "GoodsName";
            cbx.SelectedValuePath = "GoodsId";
            //cbx.SelectedItem = list.Find(g => g.GoodsId == WeighRecord.Wz);
          }
          if (bindingName.Equals("Dj"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.TextProperty, binding);
            var list = PriceModel.SelectPrice();
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "Price";
            //cbx.SelectedItem = list.Find(g => g.GoodsId == WeighRecord.Wz);
          }
          if (bindingName.Equals("Kh"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = CustomerModel.SelectCustomerByType("采购");
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "CustomerName";
            cbx.SelectedValuePath = "CustomerId";
            //cbx.SelectedItem = list.Find(c => c.CustomerId == WeighRecord.Kh);
          }
          if (bindingName.Equals("Kh2"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = CustomerModel.SelectCustomerByType("销售");
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "CustomerName";
            cbx.SelectedValuePath = "CustomerId";
            //cbx.SelectedItem = list.Find(c => c.CustomerId == WeighRecord.Kh);
          }
          if (bindingName.Equals("Kh3"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = CustomerModel.SelectCustomerByType("运输");
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "CustomerName";
            cbx.SelectedValuePath = "CustomerId";
            //cbx.SelectedItem = list.Find(c => c.CustomerId == WeighRecord.Kh);
          }
          if (bindingName.Equals("Kh4"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = CustomerModel.SelectCustomerByType("其他");
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "CustomerName";
            cbx.SelectedValuePath = "CustomerId";
            //cbx.SelectedItem = list.Find(c => c.CustomerId == WeighRecord.Kh);
          }
          if (bindingName.EndsWith("sby"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = UserModel.SelectValidUser();
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "UserName";
            cbx.SelectedValuePath = "UserId";
          }
          if (bindingName.StartsWith("By"))
          {


            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.TextProperty, binding);
            var list = SpareModel.SelectSpareByKey(f.WeighFormKey);
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "SpareValue";
            //cbx.SelectedItem = list.Find(s => s.SpareValue == WeighRecord.Ch);

          }

          sp.Children.Add(cbx);
        }
        else
        {
          RadWatermarkTextBox tbx = new RadWatermarkTextBox();

          //style
          tbx.Width = 10 * Convert.ToDouble(Global._weighConfig["MainFontSize"]) + 12;
          tbx.VerticalContentAlignment = VerticalAlignment.Center;
          //tbx.IsReadOnly = true;

          //binding
          tbx.SetBinding(TextBox.TextProperty, new Binding(bindingName));
          sp.Children.Add(tbx);
        }


        WeighFormWrapPanel.Children.Add(sp);
      }

      #endregion
    }
    #region 高级查询条件按钮事件
    private void AddCondition_Click(object sender, RoutedEventArgs e)
    {
      var conditionPanel = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(5) };

      var columnNameComboBox = new RadComboBox
      {
        Width = 60,
        Margin = new Thickness(5),
        ItemsSource = WeighFormField,
        DisplayMemberPath = "WeighFormValue",
        SelectedValuePath = "WeighFormKey"
      };

      var operatorComboBox = new RadComboBox
      {
        Width = 60,
        Margin = new Thickness(5),
        ItemsSource = new List<string> { "=", ">", "<", ">=", "<=", "<>", "LIKE" },
        SelectedValue = "="
      };

      var valueComboBox = new RadComboBox { Width = 100, Margin = new Thickness(5), IsEditable = true };
      // 设置列名选择事件处理程序
      columnNameComboBox.SelectionChanged += (s, args) =>
      {
        var selectedColumn = columnNameComboBox.SelectedValue as string;
        if (!string.IsNullOrEmpty(selectedColumn))
        {
          // 查询数据库并更新 valueComboBox 的选项
          UpdateValueComboBox(selectedColumn, valueComboBox);
        }
      };

      valueComboBox.KeyUp += Cb_KeyUp;

      var logicItems = new List<dynamic>
      {
        new { DisplayText = "且", Value = "AND" },
        new { DisplayText = "或", Value = "OR" }
      };

      var logicComboBox = new RadComboBox
      {
        Width = 60,
        Margin = new Thickness(5),
        ItemsSource = logicItems,
        DisplayMemberPath = "DisplayText",
        SelectedValuePath = "Value",
        SelectedValue = "AND"
      };

      // 创建删除按钮
      var removeButton = new Button
      {
        Content = "删除",
        Width = 60,
        Margin = new Thickness(5),
        Tag = conditionPanel
      };
      removeButton.Click += RemoveCondition_Click;

      conditionPanel.Children.Add(columnNameComboBox);
      conditionPanel.Children.Add(operatorComboBox);
      conditionPanel.Children.Add(valueComboBox);
      conditionPanel.Children.Add(logicComboBox);
      conditionPanel.Children.Add(removeButton);

      ConditionsPanel.Children.Add(conditionPanel);
    }

    private void UpdateValueComboBox(string selectedColumn, RadComboBox valueComboBox)
    {
      Console.WriteLine(selectedColumn);
      if (selectedColumn == "_ch")
      {
        var list = CarModel.SelectActiveCar();
        valueComboBox.Name = selectedColumn;
        valueComboBox.ItemsPanel = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(VirtualizingStackPanel))); //解决下拉项数量多了卡顿的问题
        valueComboBox.ItemsSource = list;
        valueComboBox.DisplayMemberPath = "PlateNo";
      }
      if (selectedColumn == "_wz")
      {
        var list = GoodsModel.SelectValidGoods();
        valueComboBox.Name = selectedColumn;
        valueComboBox.ItemsPanel = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(VirtualizingStackPanel)));
        valueComboBox.ItemsSource = list;
        valueComboBox.DisplayMemberPath = "GoodsName";
        valueComboBox.SelectedValuePath = "GoodsId";
      }
    }

    private void Cb_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
      RadComboBox cbx = sender as RadComboBox;
      string textBackup = cbx.Text; //不这样做会把cbx.Text置为null，原因不明

      switch (cbx.Name)
      {
        case "_ch":
          cbx.ItemsSource = new List<CarModel>(CarModel.SelectActiveCar(cbx.Text));
          break;
        case "_wz":
          cbx.ItemsSource = new List<GoodsModel>(GoodsModel.SelectValidGoods(cbx.Text));
          break;
        case "_kh":
          cbx.ItemsSource = new List<CustomerModel>(CustomerModel.SelectCustomerByType("采购", cbx.Text));
          break;
        case "_kh2":
          cbx.ItemsSource = new List<CustomerModel>(CustomerModel.SelectCustomerByType("销售", cbx.Text));
          break;
        case "_kh3":
          cbx.ItemsSource = new List<CustomerModel>(CustomerModel.SelectCustomerByType("运输", cbx.Text));
          break;
        case "_kh4":
          cbx.ItemsSource = new List<CustomerModel>(CustomerModel.SelectCustomerByType("其他", cbx.Text));
          break;
        default:
          break;
      }

      cbx.Text = textBackup;
      cbx.IsDropDownOpen = true;

      //输入了字符后，让光标位于字符后面
      TextBox textBox = (TextBox)cbx.Template.FindName("PART_EditableTextBox", cbx);
      textBox.SelectionStart = textBox.Text.Length;
    }

    private void RemoveCondition_Click(object sender, RoutedEventArgs e)
    {
      var button = sender as Button;
      var panel = button?.Tag as StackPanel;

      if (panel != null)
      {
        ConditionsPanel.Children.Remove(panel);
      }
    }

    private void StartGroup_Click(object sender, RoutedEventArgs e)
    {
      var startGroupPanel = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(5) };

      var startGroupTextBlock = new TextBlock { Text = "(", Margin = new Thickness(5) };

      var removeButton = new Button
      {
        Content = "删除",
        Width = 60,
        Margin = new Thickness(5)
      };

      removeButton.Click += (s, args) =>
      {
        ConditionsPanel.Children.Remove(startGroupPanel);
      };

      startGroupPanel.Children.Add(startGroupTextBlock);
      startGroupPanel.Children.Add(removeButton);

      ConditionsPanel.Children.Add(startGroupPanel);
    }

    private void EndGroup_Click(object sender, RoutedEventArgs e)
    {
      var endGroupPanel = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(5) };

      var endGroupTextBlock = new TextBlock { Text = ")", Margin = new Thickness(5) };

      var removeButton = new Button
      {
        Content = "删除",
        Width = 60,
        Margin = new Thickness(5)
      };

      removeButton.Click += (s, args) =>
      {
        ConditionsPanel.Children.Remove(endGroupPanel);
      };

      endGroupPanel.Children.Add(endGroupTextBlock);
      endGroupPanel.Children.Add(removeButton);

      ConditionsPanel.Children.Add(endGroupPanel);
    }


    #endregion
    private void QueryButton_Click(object sender, RoutedEventArgs e)
    {
      var conditions = new List<string>();
      var parameters = new DynamicParameters();

      foreach (var child in ConditionsPanel.Children)
      {
        if (child is StackPanel panel && panel.Children.Count > 0)
        {
          if (panel.Children[0] is TextBlock textBlock)
          {
            conditions.Add(textBlock.Text);
          }
          else
          {
            var columnName = ((RadComboBox)panel.Children[0]).SelectedValue as string;
            var operatorStr = ((RadComboBox)panel.Children[1]).SelectedItem as string;
            var value = ((RadComboBox)panel.Children[2]).Text as string;
            var logic = ((RadComboBox)panel.Children[3]).SelectedValue as string;

            if (!string.IsNullOrEmpty(columnName) && operatorStr != null && !string.IsNullOrEmpty(value))
            {
              var paramName = $"@{columnName}_{conditions.Count}";
              conditions.Add($"{columnName} {operatorStr} {paramName}");
              parameters.Add(paramName, value);

              // 添加逻辑操作符
              if (!string.IsNullOrEmpty(logic))
              {
                conditions.Add(logic);
              }
            }
          }
        }
      }

      if (conditions.Count > 0)
      {
        // 移除最后一个条件的逻辑操作 (AND/OR)
        var lastCondition = conditions[conditions.Count - 1];
        if (lastCondition.EndsWith("AND") || lastCondition.EndsWith("OR"))
        {
          conditions[conditions.Count - 1] = lastCondition.Substring(0, lastCondition.LastIndexOf(' '));
        }
      }

      var query = "SELECT * FROM YourTableName";
      if (conditions.Count > 0)
      {
        query += " WHERE " + string.Join(" ", conditions);
      }
      //var results = connection.Query(query, parameters);
      Console.WriteLine(query);
      foreach (var param in parameters.ParameterNames)
      {
        Console.WriteLine($"{param}: {parameters.Get<dynamic>(param)}");
      }


    }

    private void QueryButton2_Click(object sender, RoutedEventArgs e)
    {
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();
      var whereClauses = new List<string>();
      var parameters = new DynamicParameters();

      var properties = typeof(WeighRecordModel).GetProperties();

      var record = new WeighRecordModel();

      foreach (var entry in SelectedFieldDic)
      {
        if (entry.Value)
        {
          // 将键 "_ch" 转换为 "Ch"
          string propertyName = Regex.Replace(entry.Key.Substring(1), "^[a-z]", m => m.Value.ToUpper());

          // 将查询条件中选择的项目放到一个record中，随后传参给dapper
          var selectedValue = SelectedValueDic[entry.Key];
          switch (selectedValue)
          {
            case CarModel car when propertyName == "Ch":
              record.Ch = car.PlateNo;
              break;
            case GoodsModel goods when propertyName == "Wz":
              record.Wz = goods.GoodsId;
              break;
            case CustomerModel customer:
              if (propertyName.StartsWith("Kh"))
              {
                typeof(WeighRecordModel)
                    .GetProperty(propertyName)?
                    .SetValue(record, customer.CustomerId);
              }
              break;
            case SpareModel spare:
              if (propertyName.StartsWith("By"))
              {
                typeof(WeighRecordModel)
                    .GetProperty(propertyName)?
                    .SetValue(record, spare.SpareValue);
              }
              break;
            case string strValue:
              if (propertyName.Equals("IsFinish"))
              {
                typeof(WeighRecordModel)
                    .GetProperty(propertyName)?
                    .SetValue(record, strValue == "已完成");
              }
              if (propertyName.Equals("WeighTemplate"))
              {
                typeof(WeighRecordModel)
                    .GetProperty(propertyName)?
                    .SetValue(record, strValue);
              }
              break;

            default:
              break;
          }

          // 检查 WeighRecordModel 中是否存在该属性，生成sql查询语句，随后传参给dapper
          var property = Array.Find(properties, p => p.Name == propertyName);

          if (property != null)
          {
            // 获取数据库中的字段名，如果没有映射则使用属性名
            string dbFieldName = WeighRecordModel.propertyToDbFieldMap.ContainsKey(propertyName) ? WeighRecordModel.propertyToDbFieldMap[propertyName] : propertyName;

            whereClauses.Add($"{dbFieldName} = @{propertyName}");
            parameters.Add($"@{propertyName}", property.GetValue(record));
          }
        }
      }

      string whereClause = string.Join(" AND ", whereClauses);
      string sqlQuery =
        @"SELECT wr.*,
             g.goods_name AS WzName,
             c1.customer_name AS KhName, 
             c2.customer_name AS KhName,
             c3.customer_name AS Kh3Name,
             c4.customer_name AS Kh4Name,
             u1.user_name AS MzsbyName,
             u2.user_name AS PzsbyName 
          FROM 
             weighrecord wr
          LEFT JOIN goods g ON wr.wz = g.goods_id
          LEFT JOIN customer c1 ON wr.kh = c1.customer_id
          LEFT JOIN customer c2 ON wr.kh2 = c2.customer_id
          LEFT JOIN customer c3 ON wr.kh3 = c3.customer_id
          LEFT JOIN customer c4 ON wr.kh4 = c4.customer_id
          LEFT JOIN user u1 ON wr.mzsby = u1.user_id
          LEFT JOIN user u2 ON wr.pzsby = u2.user_id ";

      sqlQuery += $@"WHERE 
          (
              ( 
                  (jzsj IS NOT NULL AND jzsj >= '{StartTime}' AND jzsj <= '{EndTime}')
                  OR 
                  (jzsj IS NULL AND mzsj >= '{StartTime}' AND mzsj <= '{EndTime}') 
              )
              AND wr.is_valid = 1 
          )";

      if (whereClauses.Count > 0)
      {
        sqlQuery += " AND " + whereClause;
      }

      var list = WeighRecordModel.SelectFliterRecord(sqlQuery, parameters);

      //生成DataGrid，显示到列表中
      ResultsDataGrid.Columns.Clear();

      //根据键值对逐条设置列名、绑定对象
      foreach (var kvp in ShowFieldDic)
      {
        if (kvp.Value)
        {
          string header = string.Empty;
          if (WeighFormDic.ContainsKey(kvp.Key))
          {
            header = WeighFormDic[kvp.Key];
          }
          else
          {
            switch (kvp.Key)
            {
              case "_weighbridge1":
                header = "一次称重位置";
                break;
              case "_weighbridge2":
                header = "二次称重位置";
                break;
              case "_weighTemplate":
                header = "采购销售";
                break;
            }
          }

          // 将键 "_ch" 转换为 "Ch"
          string bindingName = Regex.Replace(kvp.Key.Substring(1), "^[a-z]", m => m.Value.ToUpper());
          if (bindingName == "Wz" || bindingName.StartsWith("Kh") || bindingName.EndsWith("sby"))
          {
            bindingName = bindingName + "Name";
          }

          DataGridTextColumn wzColumn = new DataGridTextColumn
          {
            Header = header,
            Binding = new Binding(bindingName)
          };
          ResultsDataGrid.Columns.Add(wzColumn);

        }
      }

      ResultsDataGrid.ItemsSource = list;
      stopwatch.Stop();
      Console.WriteLine($"Code executed in {stopwatch.ElapsedMilliseconds} milliseconds");
      //输出测试
      //Console.WriteLine(sqlQuery);
      //foreach (var param in parameters.ParameterNames)
      //{
      //  Console.WriteLine($"{param}: {parameters.Get<dynamic>(param)}");
      //}
    }

    private void DeleteSelected_Click(object sender, RoutedEventArgs e)
    {
      var selectedItem = ResultsDataGrid.SelectedItem;

      if (selectedItem == null)
      {
        MessageBox.Show("请先选择要删除的行！");
        return;
      }

      // 转换为数据模型
      var dataModel = selectedItem as WeighRecordModel;
      if (dataModel == null) return;

      // 数据库中逻辑删除
      dataModel.IsValid = false;
      WeighRecordModel.DeleteRecord(dataModel);

      // 从前端列表中删除
      var list = ResultsDataGrid.ItemsSource as IList;
      list?.Remove(dataModel);

      // 刷新UI
      ResultsDataGrid.Items.Refresh();
    }

    private void ExportToExcel_Click(object sender, RoutedEventArgs e)
    {
      // 检查 DataGrid 是否有数据
      if (ResultsDataGrid.Items.Count == 0)
      {
        MessageBox.Show("没有数据可导出！");
        return;
      }

      // 创建保存文件对话框
      var saveDialog = new CommonSaveFileDialog
      {
        DefaultFileName = "WeighRecords_Export",
        DefaultExtension = "xlsx",
        Filters = { new CommonFileDialogFilter("Excel Files", "*.xlsx") },
        EnsurePathExists = true,
        IsExpandedMode = true
      };

      if (saveDialog.ShowDialog() == CommonFileDialogResult.Ok)
      {
        try
        {
          AsposeHelper.InitializeAsposeCells();

          // 创建 Workbook 和 Worksheet
          Workbook workbook = new Workbook();
          Worksheet worksheet = workbook.Worksheets[0];

          // 获取 DataGrid 的列和绑定路径
          var columns = ResultsDataGrid.Columns
              .OfType<DataGridTextColumn>()
              .Select(col => new
              {
                Header = col.Header.ToString(),
                BindingPath = (col.Binding as Binding)?.Path.Path
              })
              .Where(col => !string.IsNullOrEmpty(col.BindingPath))
              .ToList();

          // 写入表头
          for (int colIdx = 0; colIdx < columns.Count; colIdx++)
          {
            worksheet.Cells[0, colIdx].PutValue(columns[colIdx].Header);
          }

          // 写入数据行
          int rowIdx = 1;
          foreach (var item in ResultsDataGrid.Items)
          {
            for (int colIdx = 0; colIdx < columns.Count; colIdx++)
            {
              string bindingPath = columns[colIdx].BindingPath;
              object value = GetPropertyValue(item, bindingPath);
              worksheet.Cells[rowIdx, colIdx].PutValue(value?.ToString() ?? "");
            }
            rowIdx++;
          }

          // 自动调整列宽
          worksheet.AutoFitColumns();

          // 保存文件
          workbook.Save(saveDialog.FileName);
          MessageBox.Show("导出成功！");
        }
        catch (Exception ex)
        {
          MessageBox.Show($"导出失败：{ex.Message}");
        }
      }
    }

    // 反射获取属性值
    private object GetPropertyValue(object obj, string propertyPath)
    {
      foreach (string part in propertyPath.Split('.'))
      {
        if (obj == null) return null;
        PropertyInfo prop = obj.GetType().GetProperty(part);
        if (prop == null) return null;
        obj = prop.GetValue(obj, null);
      }
      return obj;
    }

    private void DeleteAll_Click(object sender, RoutedEventArgs e)
    {
      // 确认对话框
      var result = MessageBox.Show(
          "确定要删除全部数据吗？此操作不可恢复！",
          "警告",
          MessageBoxButton.YesNo,
          MessageBoxImage.Warning
      );

      if (result != MessageBoxResult.Yes) return;

      try
      {
        // 获取当前数据集合
        var items = ResultsDataGrid.ItemsSource as List<WeighRecordModel>;
        if (items == null || items.Count == 0)
        {
          MessageBox.Show("当前列表无数据！");
          return;
        }

        // 高性能批量删除
        WeighRecordModel.BatchDeleteRecords(items.ToList());

        // 清空列表
        items.Clear();
        ResultsDataGrid.Items.Refresh(); // 强制刷新 UI

        MessageBox.Show("全部数据删除成功！");
      }
      catch (Exception ex)
      {
        MessageBox.Show($"删除失败：{ex.Message}");
      }
    }
  }
}
